"""
Concrete application containing the World
"""

import mjin2
import os, sys
from GameConfig import *
from GameWorld import *

class GameApplication(mjin2.InputListener, mjin2.WindowListener):
    def __init__(self, name, gameCfg, logFileName, worldFileName):
        self.cfg = gameCfg
        self.app = mjin2.Application(name, logFileName)
        self.wnd = mjin2.Window(name, self.cfg.windowConfig())
        mjin2.InputListener.__init__(self)
        mjin2.WindowListener.__init__(self)
        self.wnd.addInputListener(self)
        self.wnd.addWindowListener(self)
        dataDir = os.path.abspath(os.path.dirname(worldFileName))
        # Add to PYTHONPATH for scripts.
        self.commonScriptDir = dataDir + "/scripts/common"
        sys.path.append(self.commonScriptDir)
        self.app.pathResolver().addSearchPath(dataDir)
        self.world = World(self, self.app.pathResolver())
        self.world.load(worldFileName)
    def __del__(self):
        self.wnd.removeInputListener(self)
        self.wnd.removeWindowListener(self)
        del self.world
        del self.wnd
        del self.app

    def onInput(self, e):
        if (e.press and e.input == mjin2.INPUT_KEY_ESCAPE):
            print "ESC pressed. Shutting down."
            self.stop()

    def onWindowClose(self):
        self.stop()

    def onWindowRecreated(self):
        # Ugly implementation.
        for scene in self.world.scenes:
            scene.scene.recreateShadows()

    def run(self):
        self.world.start()
        self.wnd.run()

    def stop(self):
        print "Application.stop"
        # wnd.stop won't hurt when window is being closed
        self.wnd.stop()
        self.world.finish()

